package soar.template.springboot.service.hello.configuration.mongodb;

import java.util.Arrays;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

import soar.template.springboot.service.hello.appconfig.AppConfig;
import soar.template.springboot.service.hello.appconfig.mongodb.Config;

@Configuration
class MyMongoDBConfiguration
{
    @Resource(name = "appconfig")
    private AppConfig appconfig;

    @Bean(name = "mainMongoDbFactory")
    public MongoDbFactory mainMongoDbFactory()
    {
        return create_factory(appconfig.mongodb.main);
    }

    @Bean(name = "mainMongoTemplate")
    public MongoTemplate mainMongoTemplate()
    {
        return new MongoTemplate(mainMongoDbFactory());
    }

    private MongoDbFactory create_factory(Config config)
    {
        ServerAddress server_address = new ServerAddress(config.host,
                config.port);
        List<MongoCredential> credentials = Arrays
                .asList(MongoCredential.createCredential(config.username,
                        config.database, config.password.toCharArray()));
        MongoClientOptions.Builder builder = MongoClientOptions.builder();
        builder.connectionsPerHost(100);
        builder.threadsAllowedToBlockForConnectionMultiplier(10);
        builder.maxWaitTime(10 * 1000);
        builder.connectTimeout(10 * 1000);
        MongoClientOptions options = builder.build();
        SimpleMongoDbFactory factory = new SimpleMongoDbFactory(
                new MongoClient(server_address, credentials, options),
                config.database);
        return factory;
    }
}
